<?php
// +----------------------------------------------------------------------
// |     【PurchaseInfo】Service服务类
// +----------------------------------------------------------------------

declare (strict_types = 1);

namespace app\common\service;

use think\facade\Request;
use app\common\model\PurchaseInfo as M;
use app\common\validate\PurchaseInfo as V;
use app\common\model\PurchaseMain as P_M;
use app\common\model\StaffMain as S_M;

class PurchaseInfo{
    // 添加
    public static function goAdd($data){
        //验证
        $validate = new V;
        if(!$validate->scene('add')->check($data))
        return ['msg'=>$validate->getError(),'code'=>201];
        try {
			$data=self::dataFormat($data,'add');
            $model=M::create($data);
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }
    
    // 编辑
    public static function goEdit($data,$id){
        $data['id'] = $id;
        //验证
        $validate = new V;
        if(!$validate->scene('edit')->check($data))
        return ['msg'=>$validate->getError(),'code'=>201];
        try {
			$data=self::dataFormat($data,'edit');
             M::update($data);
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }

    // 状态
    public static function goStatus($data,$id){
        $model =  M::find($id);
        if ($model->isEmpty())  return ['msg'=>'数据不存在','code'=>201];
        try{
            $model->save($data);
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }

    // 删除
    public static function goRemove($id){
        try{
			$model = M::find($id);
            if (!$model) {
                return ['msg' => '数据不存在', 'code' => 201];
            }
			$model->delete();
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }

    // 批量删除
    public static function goBatchRemove($ids){
        try{
			M::whereIn('pur_id',$ids)->delete();
        }catch (\Exception $e){
            return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
        }
    }

    // 获取列表
    public static function goRecycle(){
        if (Request::isPost()){
            $ids = Request::param('ids');
            if (!is_array($ids)) return ['msg'=>'参数错误','code'=>'201'];
            try{
                if(Request::param('type')){
                    $data = M::onlyTrashed()->whereIn('id', $ids)->select();
                    foreach($data as $k){
                        $k->restore();
                    }
                }else{
                    M::destroy($ids,true);
                }
            }catch (\Exception $e){
                return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
            }
            return ['msg'=>'操作成功'];
        }
        //按用户名
        $where = [];
        $limit = I('get.limit/d');
        
        $list = M::onlyTrashed()->where($where)->paginate($limit);
        return ['code'=>0,'data'=>$list->items(),'extend'=>['count' => $list->total(), 'limit' => $limit]];
    }
	
	//修改某个参数
	public static function setFieldValue($data){
		$model =  M::find($data['id']);
		if ($model->isEmpty())  return ['msg'=>'数据不存在','code'=>201];
		try{
		    $model->save([
		        $data['field'] => $data['value'],
		    ]);
            
            //如果修改备注信息，则修改采购备注
            if($data['field']=='remark' && $model['exp_name']=='寄客户'){
                self::upPurchaseText($model['pur_id']);
            }
			return ['msg'=>'操作成功'];
		}catch (\Exception $e){
		    return ['msg'=>'操作失败'.$e->getMessage(),'code'=>201];
		}
	}
	
	//批量添加修改明细
	public static function write_info($info,$pur_id){
        //删除数量
        $del_count=0;
        $add_count=0;
        $count=0;
        
		foreach ($info['fabric_code'] as $i => $val) {
			if($info['fabric_code'][$i]!='' || $info['infoid'][$i]!=''){
                if($info['unit'][$i]=='米'){
                    $pur_kind=1;
                }else if($info['unit'][$i]=='条'){
                    $pur_kind=2;
                }else if($info['unit'][$i]=='块'){
                    $pur_kind=3;
                }else if($info['unit'][$i]=='KG'){
                    $pur_kind=4;
                }else if($info['unit'][$i]=='样'){
                    $pur_kind=5;
                }
				$data=[
                    'fabric_id'=>$info['fabric_id'][$i],
					'fabric_code'=>$info['fabric_code'][$i],
					'fabric_name'=>$info['fabric_name'][$i],
					'color_code'=>$info['color_code'][$i],
					'color_name'=>$info['color_name'][$i],
					'color_hex'=>$info['color_hex'][$i],
                    'sup_name'=>$info['sup_name'][$i],
                    'sup_id'=>$info['sup_id'][$i],
					'sup_code'=>$info['sup_code'][$i],
					'sup_color'=>$info['sup_color'][$i],
                    'exp_method'=>$info['exp_method'][$i],
                    'exp_name'=>$info['exp_name'][$i],
                    'cut_payment'=>$info['cut_payment'][$i],
                    'pur_kind'=>$pur_kind,
					'count'=>$info['count'][$i],
                    'unit'=>$info['unit'][$i],
                    'gray'=>$info['gray'][$i],
                    'remark'=>$info['remark'][$i],
				];
				if($info['infoid'][$i]==""){
					$data['pur_id']=$pur_id;
					self::goAdd($data);
                    $add_count++;
				}else{
					$id=$info['infoid'][$i];
					if($data['fabric_code']=='' && $data['fabric_name']==''){
						self::goRemove($id);
                        $del_count++;
					}else{
						self::goEdit($data,$id);
					}
				}
                $count++;
			}
		}
        
        //判断是否没有采购信息，没有删除主单
        $info_count=M::where('pur_id', $pur_id)->count();
        if($info_count==0){
            P_M::destroy($pur_id, true);
        }
	}
    
    // 更新采购文案信息
    public static function upPurchaseText($id) {
        $purchase = P_M::find($id);
        
        if(!$purchase) return false;
        
        $staff = S_M::where('id', $purchase['staff_id'])->find();
        $staff_name = $staff['short_name'] ?? '';
        $store_name = $staff['store_name'] ?? '';
        $pur_type = $purchase['pur_type'] ?? 1;
        $need_exp_store = ['富民','国际'];
        $self_pickup = !in_array($store_name, $need_exp_store);
    
        $info = M::where(['pur_id' => $id])
            ->order('unit desc')
            ->select()
            ->toArray();
    
        $sketch = $delivery = $pick_info = '';
    
        if ($info) {
            $fabricGroups = self::groupItems($info, 'fabric_code');
            $supGroups = self::groupItems($info, 'sup_code');
            $lastFabricKey = array_key_last($fabricGroups);
            $lastSupKey = array_key_last($supGroups);
    
            $get_suffix = static function($items, $sn, $isLast = false) use ($pur_type, $self_pickup) {
                $lineEnding = $isLast ? "" : "\n\n";
                if ($pur_type == 0) {
                    return "【先报公斤数，确认后再安排】\n（{$sn}）{$lineEnding}";
                } else if ($pur_type == 1) {
                    foreach ($items as $item) {
                        if ($self_pickup) {
                            return "自提（{$sn}）{$lineEnding}";
                        } else if ($item['exp_method'] == '中大提发' || $item['exp_name'] == '客户提' || $item['exp_name'] == '寄客户') {
                            return "自提（{$sn}）{$lineEnding}";
                        } else {
                            return "--------------------------\n过东莞 - 陈伟聪 收\n（{$sn}）{$lineEnding}";
                        }
                    }
                }
            };
    
            // 处理面料分组（sketch）
            foreach ($fabricGroups as $code => $items) {
                $isLast = ($code === $lastFabricKey);
                $sketch .= self::buildSection(
                    $code,
                    $items,
                    $staff_name,
                    function($items, $sn) { return ""; }, // 返回空字符串，不添加任何后缀
                    'color_code'
                );
            }
    
            // 处理供应商分组（delivery）
            foreach ($supGroups as $code => $items) {
                $isLast = ($code === $lastSupKey);
                $delivery .= self::buildSection(
                    $code,
                    $items,
                    $staff_name,
                    function($items, $sn) use ($get_suffix, $isLast) {
                        return $get_suffix($items, $sn, $isLast);
                    },
                    'sup_color'
                );
            }
    
            // 新增：生成 pick_info 提货信息
            $hasJikehu = false;
            foreach ($info as $item) {
                if ($item['exp_name'] == '寄客户') {
                    $hasJikehu = true;
                    break;
                }
            }
    
            if ($hasJikehu) {
                // 获取第一个记录的 sup_name 和 remark
                $firstSupName = $info[0]['sup_name'] ?? '';
                $firstRemark = $info[0]['remark'] ?? '';
                
                $pick_info = "{$firstSupName}提一下，改标签，寄快递\n\n";
                $pick_info .= $sketch . "\n";
                $pick_info .= "收货信息：" . $firstRemark;
            }
        }
    
        // 更新数据库，包括新增的 pick_info 字段
        P_M::where('id', $id)->update([
            'sketch' => $sketch, 
            'delivery' => $delivery, 
            'pick_info' => $pick_info
        ]);
        
        return compact('sketch', 'delivery', 'pick_info');
    }
    
    private static function groupItems($items, $groupField) {
        $groups = [];
        foreach ($items as $item) {
            $groups[$item[$groupField]][] = $item;
        }
        return $groups;
    }
    
    private static function buildSection($code, $items, $staffName, $get_suffix, $codeField) {
        // 新增供应商名称行（从分组中第一个 item 的 sup_name 获取）
        $supName = $items[0]['sup_name'] ?? ''; // 假设数据中有 sup_name 字段
        $section = '';
        // if($supName!='') $section .= "[ {$supName} ]\n";  // 添加供应商名称行
        $section .= $code . ' # ' . $items[0]['fabric_name'] . "\n"; // 原编号行
        
        foreach ($items as $item) {
            if ($item['unit'] == '块') {
                $count = '';
                $unit = 'A4';
            } else if ($item['unit'] == '样') {
                $count = '';
                $unit = '大货样（写缸号）';
            } else {
                $count = $item['count'];
                $unit = $item['unit'];
            }
            $section .= sprintf("%-20s %s%s\n",
                $item[$codeField] . '#' . $item['color_name'],
                $count,
                $unit
            );
        }
        
        $section .= $get_suffix($items, $staffName);
        return $section;
    }
	
	// 预处理添加和修改的数据
	public static function dataFormat($data,$type='add'){
		if($type == 'add'){					//添加时才处理

		}else if($type == 'edit'){			//修改时才处理
			
		}
		return $data;
	}
}
